<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import { Button, message, Progress, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';

import { getMyQueueInfo, getQueueList, getQueueStatus } from '#/api/booking';

const router = useRouter();

const refreshing = ref(false);
const lastUpdateTime = ref('');
const serviceWindows = ref([]);
const myQueueInfo = ref(null);
const queueList = ref([]);
const notifications = ref([]);

let refreshTimer: NodeJS.Timeout | null = null;

const refreshStatus = async () => {
  try {
    refreshing.value = true;

    // 并行加载所有数据
    const [statusData, queueInfo, queueListData] = await Promise.all([
      getQueueStatus(),
      getMyQueueInfo(),
      getQueueList(),
    ]);

    serviceWindows.value = statusData.windows;
    myQueueInfo.value = queueInfo;
    queueList.value = queueListData;

    lastUpdateTime.value = dayjs().format('HH:mm:ss');
  } catch (error) {
    console.error('刷新状态失败:', error);
    message.error('刷新状态失败');
  } finally {
    refreshing.value = false;
  }
};

const getWindowStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    BUSY: 'green',
    IDLE: 'blue',
    OFFLINE: 'red',
  };
  return colorMap[status] || 'default';
};

const getWindowStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    BUSY: '服务中',
    IDLE: '空闲',
    OFFLINE: '离线',
  };
  return textMap[status] || '未知';
};

const getQueueStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    WAITING: 'orange',
    CALLED: 'green',
    COMPLETED: 'default',
  };
  return colorMap[status] || 'default';
};

const getQueueStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    WAITING: '等待中',
    CALLED: '已叫号',
    COMPLETED: '已完成',
  };
  return textMap[status] || '未知';
};

const getNotificationIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    info: 'mdi:information',
    warning: 'mdi:alert',
    success: 'mdi:check-circle',
  };
  return iconMap[type] || 'mdi:information';
};

const getProgressPercent = (position: number, total: number) => {
  if (total === 0) return 0;
  return Math.round(((total - position + 1) / total) * 100);
};

const formatTime = (time: string) => {
  return dayjs(time).format('HH:mm:ss');
};

const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    refreshStatus();
  }, 10_000); // 每10秒刷新一次
};

const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

const goToBooking = () => {
  router.push('/booking');
};

const goToMyBookings = () => {
  router.push('/booking/my-bookings');
};

onMounted(() => {
  refreshStatus();
  startAutoRefresh();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<template>
  <div class="queue-page">
    <div class="queue-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">排队状态</h1>
        <p class="page-subtitle">实时查看您的排队情况</p>
      </div>

      <!-- 我的排队信息 -->
      <div v-if="myQueueInfo" class="my-queue-section">
        <div class="my-queue-card">
          <div class="queue-header">
            <h2>我的排队</h2>
            <div class="refresh-info">
              <span>最后更新: {{ lastUpdateTime }}</span>
              <Button @click="refreshStatus" :loading="refreshing" size="small">
                <IconifyIcon icon="mdi:refresh" />
              </Button>
            </div>
          </div>

          <div class="queue-content">
            <div class="ticket-display">
              <div class="ticket-number">{{ myQueueInfo.ticketNumber }}</div>
              <div class="ticket-label">我的号码</div>
            </div>

            <div class="queue-details">
              <div class="detail-item">
                <span class="label">排队位置：</span>
                <span class="value position">{{ myQueueInfo.position }}</span>
              </div>
              <div class="detail-item">
                <span class="label">预计等待：</span>
                <span class="value wait-time">{{
                  myQueueInfo.estimatedWaitTime
                }}</span>
              </div>
              <div class="detail-item">
                <span class="label">服务窗口：</span>
                <span class="value window">{{
                  myQueueInfo.serviceWindow
                }}</span>
              </div>
            </div>
          </div>

          <div class="queue-progress">
            <div class="progress-info">
              <span>前面还有 {{ myQueueInfo.position - 1 }} 人</span>
              <span>预计 {{ myQueueInfo.estimatedWaitTime }} 后到您</span>
            </div>
            <Progress
              :percent="
                getProgressPercent(
                  myQueueInfo.position,
                  myQueueInfo.totalInQueue,
                )
              "
              :show-info="false"
              stroke-color="#3b82f6"
              stroke-width="8"
            />
          </div>
        </div>
      </div>

      <!-- 当前服务状态 -->
      <div class="current-service-section">
        <h2 class="section-title">当前服务</h2>
        <div class="service-windows">
          <div
            v-for="window in serviceWindows"
            :key="window.id"
            class="service-window"
          >
            <div class="window-header">
              <h3 class="window-name">{{ window.name }}</h3>
              <Tag :color="getWindowStatusColor(window.status)">
                {{ getWindowStatusText(window.status) }}
              </Tag>
            </div>

            <div v-if="window.currentCustomer" class="current-customer">
              <div class="customer-info">
                <span class="ticket-number">{{
                  window.currentCustomer.ticketNumber
                }}</span>
                <span class="customer-name">{{
                  window.currentCustomer.customerName
                }}</span>
              </div>
              <div class="service-time">
                <span class="label">服务开始：</span>
                <span class="time">{{
                  formatTime(window.currentCustomer.startTime)
                }}</span>
              </div>
            </div>

            <div v-else class="no-customer">
              <IconifyIcon icon="mdi:account-off" />
              <span>暂无客户</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 排队列表 -->
      <div class="queue-list-section">
        <h2 class="section-title">排队列表</h2>
        <div class="queue-list">
          <div
            v-for="(item, index) in queueList"
            :key="item.ticketNumber"
            class="queue-item"
            :class="{
              'my-ticket': item.ticketNumber === myQueueInfo?.ticketNumber,
            }"
          >
            <div class="queue-position">{{ index + 1 }}</div>
            <div class="queue-ticket">
              <span class="ticket-number">{{ item.ticketNumber }}</span>
              <span class="customer-name">{{ item.customerName }}</span>
            </div>
            <div class="queue-status">
              <Tag :color="getQueueStatusColor(item.status)">
                {{ getQueueStatusText(item.status) }}
              </Tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 通知消息 -->
      <div v-if="notifications.length > 0" class="notifications-section">
        <h2 class="section-title">通知消息</h2>
        <div class="notifications-list">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="notification-item"
            :class="notification.type"
          >
            <IconifyIcon :icon="getNotificationIcon(notification.type)" />
            <span class="notification-text">{{ notification.message }}</span>
            <span class="notification-time">{{
              formatTime(notification.time)
            }}</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions-section">
        <Button type="primary" size="large" @click="goToBooking">
          <IconifyIcon icon="mdi:calendar-plus" />
          预约服务
        </Button>
        <Button size="large" @click="goToMyBookings">
          <IconifyIcon icon="mdi:calendar-clock" />
          我的预约
        </Button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.queue-page {
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.queue-container {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
  color: white;
  text-align: center;
}

.page-title {
  margin: 0 0 8px;
  font-size: 32px;
  font-weight: 700;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.my-queue-section {
  margin-bottom: 32px;
}

.my-queue-card {
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgb(0 0 0 / 20%);
}

.queue-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.queue-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.refresh-info {
  display: flex;
  gap: 12px;
  align-items: center;
  font-size: 14px;
  color: #6b7280;
}

.queue-content {
  display: flex;
  gap: 32px;
  align-items: center;
  margin-bottom: 24px;
}

.ticket-display {
  text-align: center;
}

.ticket-number {
  font-size: 64px;
  font-weight: 700;
  line-height: 1;
  color: #3b82f6;
}

.ticket-label {
  margin-top: 8px;
  font-size: 16px;
  color: #6b7280;
}

.queue-details {
  flex: 1;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  font-size: 16px;
  color: #6b7280;
}

.detail-item .value {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.detail-item .value.position {
  color: #f59e0b;
}

.detail-item .value.wait-time {
  color: #10b981;
}

.queue-progress {
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #6b7280;
}

.current-service-section,
.queue-list-section,
.notifications-section {
  margin-bottom: 32px;
}

.section-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
  color: white;
  text-align: center;
}

.service-windows {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.service-window {
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
}

.window-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.window-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.current-customer {
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
}

.customer-info {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.ticket-number {
  font-size: 20px;
  font-weight: 700;
  color: #3b82f6;
}

.customer-name {
  font-weight: 500;
  color: #1f2937;
}

.service-time {
  font-size: 14px;
  color: #6b7280;
}

.service-time .label {
  margin-right: 4px;
}

.no-customer {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: center;
  padding: 32px;
  font-size: 16px;
  color: #6b7280;
  text-align: center;
}

.queue-list {
  overflow: hidden;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
}

.queue-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
}

.queue-item:last-child {
  border-bottom: none;
}

.queue-item.my-ticket {
  background: #f0f9ff;
  border-left: 4px solid #3b82f6;
}

.queue-position {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-right: 20px;
  font-size: 18px;
  font-weight: 700;
  color: #6b7280;
  background: #f3f4f6;
  border-radius: 50%;
}

.queue-ticket {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 4px;
}

.queue-ticket .ticket-number {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.queue-ticket .customer-name {
  font-size: 14px;
  color: #6b7280;
}

.notifications-list {
  overflow: hidden;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
}

.notification-item {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-item.info {
  background: #f0f9ff;
}

.notification-item.warning {
  background: #fffbeb;
}

.notification-item.success {
  background: #f0fdf4;
}

.notification-text {
  flex: 1;
  font-size: 16px;
  color: #1f2937;
}

.notification-time {
  font-size: 14px;
  color: #6b7280;
}

.actions-section {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 32px;
}

.actions-section .ant-btn {
  min-width: 160px;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}
</style>
